package com.mgq.netty.c10;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;

/**
 * @author MaGuangQi
 * netty帮助我们实现了http协议的编码和解码
 * @date 2021-12-06 17:02
 **/
@Slf4j
public class TestNettyHttpServer {
    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, worker);
            serverBootstrap.channel(NioServerSocketChannel.class);
            ChannelFuture future = serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                    ch.pipeline().addLast(new HttpServerCodec());
                    //netty提供了SimpleChannelInboundHandler<T>,来获取处理指定的类型
                    //比如我们只处理 HttpRequest, SimpleChannelInboundHandler<HttpRequest>
                    ch.pipeline().addLast(new SimpleChannelInboundHandler<HttpRequest>() {
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
                           log.debug("请求的url是{}",msg.uri());
                           log.debug("请求的ip是{}",msg.method());
                            DefaultFullHttpResponse  response = new DefaultFullHttpResponse (msg.protocolVersion(), HttpResponseStatus.OK);
                            byte[] bytes = "<h1>HELLO,WORLD<h1/>".getBytes(StandardCharsets.UTF_8);
                            response.headers().set(CONTENT_LENGTH, bytes.length);
                            response.content().writeBytes(bytes);
                            ctx.channel().writeAndFlush(response);
                        }
                    });
                    //如果只处理HttpRequest和SimpleChannelInboundHandler<HttpRequest>等价
                   /* ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            // msg的类型,class io.netty.handler.codec.http.DefaultHttpRequest 请求头
                            //msg的类型,class io.netty.handler.codec.http.LastHttpContent$1 请求体
                            if (msg instanceof HttpRequest) {

                            } else if (msg instanceof HttpContent) {

                            }
                            log.debug("msg的类型,{}",msg.getClass());
                        }
                    });*/
                }
            }).bind(8080).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("server error", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

}
